package com.ddwl.user.repository.impl;

import com.ddwl.schema.bo.base.LocationBo;
import com.ddwl.schema.model.Location;
import com.ddwl.user.dao.model.Device;
import com.ddwl.user.repository.DeviceRepositoryAdvance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2021/6/2 9:11
 */
public class DeviceRepositoryImpl implements DeviceRepositoryAdvance {

    @Autowired
    private MongoTemplate template;

    @Override
    public void batchUpdateLoc(List<String> macs, Location loc) {
        template.updateMulti(Query.query(Criteria.where("mac").in(macs)), Update.update("loc", loc), Device.class);
    }

    @Override
    public List<Device> near(LocationBo loc, String platform) {
        Point point = new Point(loc.getLng(), loc.getLat());
        NearQuery near = NearQuery.near(point, Metrics.KILOMETERS).spherical(true).query(Query.query(Criteria.where("platform").is(platform)))
                .with(PageRequest.of(0, 100)).maxDistance(5, Metrics.KILOMETERS);
        AggregationOperation operation = Aggregation.geoNear(near, "distance");
        AggregationResults<Device> aggregationResults = template.aggregate(Aggregation.newAggregation(Device.class, operation), Device.class);
        return aggregationResults.getMappedResults();
    }
}
